package hu.jonas.allunit.source;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.junit.buildpath.BuildPathSupport;
import org.eclipse.jdt.launching.JavaRuntime;

public class ProjectHelper {

	@SuppressWarnings("restriction")
	public static IJavaProject createProject(String name) throws CoreException {
		IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
		
		IProject project = root.getProject(name);
		project.create(null);
		project.open(null);
		
		IProjectDescription description = project.getDescription();
		description.setNatureIds(new String[] { JavaCore.NATURE_ID });
		project.setDescription(description, null);
		
		IJavaProject javaProject = JavaCore.create(project);
		
		// Output folder
		IFolder bin = project.getFolder("bin");
		javaProject.setOutputLocation(bin.getFullPath(), null);
		
		IFolder src = project.getFolder("src");
		if (!src.exists()) {
			src.create(true, true, null);
		}
		
		// Setting classpath
		List<IClasspathEntry> classpath = new ArrayList<IClasspathEntry>();
		
		classpath.add(JavaRuntime.getDefaultJREContainerEntry());
		classpath.add(BuildPathSupport.getJUnit4ClasspathEntry());
		classpath.add(JavaCore.newSourceEntry(src.getFullPath()));
		
		javaProject.setRawClasspath(classpath.toArray(new IClasspathEntry[classpath.size()]), null);
		
		return javaProject;
	}
	
	public static IPackageFragment createPackage(IJavaProject javaProject, String name)
			throws CoreException {
		
		IFolder src = javaProject.getProject().getFolder("src");
		IPackageFragmentRoot root = javaProject.getPackageFragmentRoot(src);
		
		return root.createPackageFragment(name, true, null);
	}
	
	public static void createType(IPackageFragment packageFragment, String fileName, String source) throws JavaModelException {
		packageFragment.getCompilationUnit(fileName).createType(source, null, true, null);
	}
	
}
